package com.xmtlxx.web.controller.wms.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import com.xmtlxx.web.controller.center.service.ICenterService;
import com.xmtlxx.web.controller.center.vo.SendTaskVo;
import com.xmtlxx.web.controller.oms.service.IDisposalTaskService;
import com.xmtlxx.web.controller.oms.service.ITaskService;
import com.xmtlxx.web.controller.wms.service.IDealService;
import com.xmtlxx.common.annotation.Log;
import com.xmtlxx.common.annotation.RepeatSubmit;
import com.xmtlxx.common.core.controller.BaseController;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.domain.R;
import com.xmtlxx.common.core.domain.entity.SysDictData;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.core.validate.AddGroup;
import com.xmtlxx.common.core.validate.EditGroup;
import com.xmtlxx.common.core.validate.QueryGroup;
import com.xmtlxx.common.enums.BusinessType;
import com.xmtlxx.common.helper.LoginHelper;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.common.utils.poi.ExcelUtil;
import com.xmtlxx.oms.domain.bo.TaskBo;
import com.xmtlxx.oms.domain.vo.TaskVo;
import com.xmtlxx.system.domain.SysOss;
import com.xmtlxx.system.domain.bo.SysOssBo;
import com.xmtlxx.system.service.ISysDictDataService;
import com.xmtlxx.system.service.ISysOssService;
import com.xmtlxx.wms.domain.bo.DealBo;
import com.xmtlxx.wms.domain.bo.DealDtlBo;
import com.xmtlxx.wms.domain.vo.DealDtlVo;
import com.xmtlxx.wms.domain.vo.DealVo;
import com.xmtlxx.wms.service.IDealDtlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;

/**
 * 处置Controller
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Validated
@Api(value = "处置控制器", tags = {"处置管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/wms/deal")
public class DealController extends BaseController {

    private final IDealService iDealService;

    private final IDisposalTaskService iDisposalTaskService;

    private final IDealDtlService iDealDtlService;

    private final ISysDictDataService iSysDictDataService;

    private final ITaskService iTaskService;

    private final ICenterService centerService;

    private final ISysOssService ossService;

    /**
     * 返回一个初始化的对象到前端，方便进行动态渲染
     */
    @ApiOperation("用于返回一个初始化对象")
    @PostMapping("/initBean")
    R<DealVo> initBean(){
        DealVo vo = new DealVo();
        //可以对数据进行初始化
        return R.ok(vo);
    }

    @ApiOperation("用于返回一个初始化对象")
    @GetMapping("/initDealType")
    R<List<Map<String,Object>>> initDealType(){
        SysDictData dictData = new SysDictData();
        dictData.setDictType("wms_deal_type");

        List<Map<String,Object>> items = new ArrayList<>();

        List<SysDictData> dictDataList = iSysDictDataService.selectDictDataList(dictData);

        Map<String,Object> first = new HashMap<>();

        first.put("label","全部");
        first.put("value",null);
        Map<String,Object> sbadge = new HashMap<>();
        sbadge.put("value",null);
        first.put("badge",sbadge);
        items.add(first);

        if(dictDataList != null && dictDataList.size() > 0){
           for (SysDictData sysDictData:dictDataList){
               Map<String,Object> item = new HashMap<>();
               item.put("label",sysDictData.getDictLabel());
               item.put("value",sysDictData.getDictValue());
               Map<String,Object> badge = new HashMap<>();
               badge.put("value",null);
               item.put("badge",badge);
               items.add(item);
           }
        }


        //可以对数据进行初始化
        return R.ok(items);
    }

    @ApiOperation("用于返回一个初始化对象")
    @GetMapping("/initDealBean/{ids}")
    R<TaskVo> initDealBean(@ApiParam("主键串")
                           @NotEmpty(message = "主键不能为空")
                           @PathVariable List<String> ids){


        return R.ok(iDealService.initDealBean(ids));
    }

    /**
     * 查询处置列表
     */
    @ApiOperation("查询处置列表")
//    @SaCheckPermission("wms:deal:list")
    @GetMapping("/list")
    public TableDataInfo<DealVo> list(@Validated(QueryGroup.class) DealBo bo, PageQuery pageQuery) {
        if(LoginHelper.getLoginUser().getRolePermission().contains("centercangguang") && StringUtils.isNotEmpty(bo.getSource()) && bo.getSource().equals("app")){
            bo.setIsTrailer("1");
        }
        return iDealService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询处置列表
     */
    @ApiOperation("物品处置信息列表")
//    @SaCheckPermission("wms:deal:list")
    @GetMapping("/dealDtlList")
    public TableDataInfo<DealDtlVo> dealDtlList(@Validated(QueryGroup.class) DealDtlBo bo, PageQuery pageQuery) {
        return iDealDtlService.pageList(bo,pageQuery);
    }

    /**
     * 查询处置列表
     */
    @ApiOperation("物品处置信息列表")
    @GetMapping("/dealDtlListNew")
    public TableDataInfo<DealDtlVo> dealDtlListNew(@Validated(QueryGroup.class) DealDtlBo bo, PageQuery pageQuery) {
        return iDealDtlService.dealDtlListNew(bo,pageQuery);
    }

    /**
     * 导出处置列表
     */
    @ApiOperation("导出处置列表")
    @SaCheckPermission("wms:deal:export")
    @Log(title = "处置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@Validated DealBo bo, HttpServletResponse response) {
        List<DealVo> list = iDealService.queryList(bo);
        ExcelUtil.exportExcel(list, "处置", DealVo.class, response);
    }

    /**
     * 获取处置详细信息
     */
    @ApiOperation("获取处置详细信息")
//    @SaCheckPermission("wms:deal:query")
    @GetMapping("/{id}")
    public R<DealVo> getInfo(@ApiParam("主键")
                                     @NotNull(message = "主键不能为空")
                                     @PathVariable("id") String id) {
        DealVo vo = iDealService.queryById(id);
        DealDtlBo dealDtlBo = new DealDtlBo();
        dealDtlBo.setDealId(vo.getId());
        vo.setItems(iDealDtlService.queryList(dealDtlBo));
        SysOssBo oss = new SysOssBo();
        oss.setObjid(vo.getId());
        oss.setBuss("deal_register");
        List<SysOss> ossList = ossService.selectSysOssList(oss);
        if(ossList != null && ossList.size() > 0){
            vo.setOss(ossList);
        }else {
            vo.setOss(new ArrayList<>());
        }
        if(!StringUtils.isEmpty(vo.getTaskId())){
            TaskVo taskVo = new TaskVo();
            taskVo.setId(vo.getTaskId());
          //  taskVo = iDisposalTaskService.initBean(taskVo);
            vo.setTaskVo(taskVo);
        }
        return R.ok(vo);
    }

    /**
     * 新增处置
     */
    @ApiOperation("新增处置")
    @SaCheckPermission("wms:deal:add")
    @Log(title = "处置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DealVo vo) {
        DealBo bo = new DealBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iDealService.insertByBo(bo) != null ? 1 : 0);

    }

    /**
     * 修改处置
     */
    @ApiOperation("修改处置")
    @SaCheckPermission("wms:deal:edit")
    @Log(title = "处置", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    @Transactional(rollbackFor = Exception.class)
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DealVo vo) {
        DealBo bo = new DealBo();
        BeanUtil.copyProperties(vo,bo);
        Integer flag = iDealService.updateByDealBo(bo) != null ? 1 : 0;
        if(flag == 1){
            boolean isUpdate = true;
            DealBo dealBo = new DealBo();
            dealBo.setTaskId(bo.getTaskId());
            List<DealVo> dealVos = iDealService.queryList(dealBo);
            if(dealVos != null && dealVos.size() > 0){
                for (DealVo item:dealVos){
                    //判断是否都已审核，已审核及更新申请单的审核状态
                    if(!item.getIsCheck().equals("1")){
                        isUpdate = false;
                    }
                }
                if(isUpdate){
                    //更新审核状态
                    TaskVo task = iTaskService.queryById(bo.getTaskId());
                    if(task != null){
                        TaskBo taskBo = new TaskBo();
                        BeanUtil.copyProperties(task,taskBo);
                        taskBo.setCheckStatus("1");
                        taskBo.setChecker(LoginHelper.getNickname());
                        taskBo.setCheckTime(new Date());
                        iTaskService.updateTaskEnty(taskBo);

                        //自行配送下发
                        if(taskBo.getDelivery().equals("1")){
                            SendTaskVo sendTaskVo = new SendTaskVo();
                            sendTaskVo.setStoreId(taskBo.getStoreId());
                            sendTaskVo.setCarrierDeptId(0l);
                            String[] ids = new String[]{taskBo.getId()};
                            sendTaskVo.setIds(ids);
                            centerService.sendsTask(sendTaskVo);
                        }

                    }
                }
            }

        }
        return toAjax(flag);
    }

    /**
     * 处置确认
     */
    @ApiOperation("处置确认")
    @SaCheckPermission("wms:deal:edit")
    @Log(title = "处置", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/validate")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> validate(@Validated(AddGroup.class) @RequestBody DealVo vo) {
        DealBo bo = new DealBo();
        BeanUtil.copyProperties(vo,bo);
        return toAjax(iDealService.validateDeal(bo) != null ? 1 : 0);

    }

    /**
     * 删除处置
     */
    @ApiOperation("删除处置")
    @SaCheckPermission("wms:deal:remove")
    @Log(title = "处置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @Transactional(rollbackFor = Exception.class)
    public R<Void> remove(@ApiParam("主键串")
                          @NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(iDealService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }
}
